<?php
namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Jobs\OrdersNotify;
use App\Models\Order;
use Illuminate\Http\Request;

class OrdersController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth:user');
    }

    public function index(Request $request)
    {
        $tradeNo = $request->input('trade_no');
        $title = $request->input('title');
        $smoney = $request->input('smoney');
        $emoney = $request->input('emoney');
        $status = $request->input('status');
        $gateway = $request->input('gateway');
        $merchantId = $request->input('merchant_id');

        $builder = Order::query();
        $builder->where('user_id', $request->user('user')->id);
        if (!is_null($merchantId)) {
            $builder->where('merchant_id', $merchantId);
        }
        if (!is_null($tradeNo)) {
            $builder->where(function ($query) use($tradeNo) {
                $query->where('trade_no', $tradeNo);
                $query->orWhere('out_trade_no', $tradeNo);
            });
        }
        if (!is_null($title)) {
            $builder->where('title', 'like', '%' . $title . '%');
        }
        if (!is_null($status)) {
            $builder->where('status', $status);
        }
        if (!is_null($gateway)) {
            $builder->where('gateway', $gateway);
        }
        if (!is_null($smoney) && !is_null($emoney)) {
            $builder->whereBetween('total_amount' ,[$smoney, $emoney]);
        }
        $builder->latest();
        $orders = $builder->paginate(10);
        return view('user.orders.index', compact('orders'));
    }

    public function show(Order $order)
    {
        dd($order);
    }

    public function notify(Order $order)
    {
        $this->authorize('own', $order);
        OrdersNotify::dispatch($order);
        return response()->json(['code' => 200]);
    }
}
